package com.gitee.zjbqdzq.core;

import cn.hutool.core.util.RuntimeUtil;
import com.gitee.zjbqdzq.Commander;

import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class FfmpegDownloader extends Downloader {

    private final Commander commander;

    public FfmpegDownloader(Commander commander) throws IOException {
        super(commander.getSaveFolder());
        this.commander = commander;
    }

    @Override
    public void download(String url, String filename) throws IOException {
        String finalFilename;
        if (commander.isM3u8()) {
            finalFilename = Paths.get(saveFolder, filename, "index.m3u8").toString();
            checkSaveFolder(Paths.get(saveFolder, filename).toString());
        } else {
            finalFilename = Paths.get(saveFolder, filename + ".mp4").toString();
        }
        System.out.printf("开始下载 %s %n", url);
        Path path = Paths.get(finalFilename);
        if (Files.exists(path)) {
            System.out.printf("文件已存在 %s %n", finalFilename);
            return;
        }
        Process ffmpeg;
        if (commander.isM3u8()) {
            ffmpeg = RuntimeUtil.exec("ffmpeg", "-i", url, "-codec:", "copy", "-start_number", "0", "-hls_time", "10", "-hls_list_size", "0", "-f", "hls", finalFilename);
        } else {
            ffmpeg = RuntimeUtil.exec("ffmpeg", "-i", url, "-codec:", "copy", finalFilename);
        }
        try (BufferedReader bufferedReader = ffmpeg.inputReader()) {
            while ((bufferedReader.readLine()) != null) {
            }
        }
        if (ffmpeg.exitValue() == 0) {
            System.out.printf("文件 %s 下载成功%n", finalFilename);
        } else {
            Files.deleteIfExists(path);
            System.err.printf("文件 %s 下载失败%n", finalFilename);
            byte[] bytes = ffmpeg.getErrorStream().readAllBytes();
            System.err.printf("原因: %s%n", new String(bytes));
        }
    }
}
